<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>预登记详情</span>
        <el-button style="float: right; margin-left: 10px; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
        <el-button style="float: right; padding: 3px 0" type="text" @click="refreshData">
          <i class="el-icon-refresh"></i> 刷新数据
        </el-button>
      </div>
      
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请编号" :span="2">{{ preRegisterInfo.registerId }}</el-descriptions-item>
        <el-descriptions-item label="申请状态" :span="2">
          <el-tag :type="getStatusType(preRegisterInfo.status)">
            {{ getStatusText(preRegisterInfo.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间" :span="2">{{ preRegisterInfo.createTime }}</el-descriptions-item>
        <el-descriptions-item v-if="preRegisterInfo.status === '2'" label="拒绝原因" :span="2">
          {{ preRegisterInfo.rejectReason || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ preRegisterInfo.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 入住信息 -->
      <div class="section-container" v-if="preRegisterInfo.status === '4'">
        <div class="section-title">
          <el-divider content-position="left">入住信息</el-divider>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="入住开始日期">{{ preRegisterInfo.checkInStart }}</el-descriptions-item>
          <el-descriptions-item label="入住结束日期">{{ preRegisterInfo.checkInEnd }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <!-- 租金信息 -->
      <div class="section-container" v-if="preRegisterInfo.status === '4' && rentObjectData">
        <div class="section-title">
          <el-divider content-position="left">租金信息</el-divider>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="租金">{{ rentObjectData.rent }} 元</el-descriptions-item>
          <el-descriptions-item label="押金">{{ rentObjectData.deposit }} 元</el-descriptions-item>
          <el-descriptions-item label="租金类型">{{ getRentCollectCycleText(rentObjectData.rentCollectCycle) }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ getRentTypeText(rentObjectData.rentType) }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <!-- 主申请人信息 -->
      <div class="section-container" v-if="preRegisterInfo.mainRenter">
        <div class="section-title">
          <el-divider content-position="left">主申请人信息</el-divider>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <div class="info-label">姓名：</div>
              <div class="info-value">{{ preRegisterInfo.mainRenter.name }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <div class="info-label">手机号：</div>
              <div class="info-value">{{ preRegisterInfo.mainRenter.contacts }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <div class="info-label">身份证号：</div>
              <div class="info-value">{{ preRegisterInfo.mainRenter.idCardNumber }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <div class="info-label">房客类型：</div>
              <div class="info-value">
                <el-tag :type="preRegisterInfo.mainRenter?.renterType === '1' ? 'success' : 'primary'">
                  {{ preRegisterInfo.mainRenter?.renterType === '1' ? '省内房客' : preRegisterInfo.mainRenter?.renterType === '2' ? '省外房客' : '--' }}
                </el-tag>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row v-if="preRegisterInfo.mainRenter.picUrl">
          <el-col :span="24">
            <div class="info-item">
              <div class="info-label">证件照片：</div>
              <div class="info-value">
                <el-image 
                  style="width: 120px; height: 120px" 
                  :src="preRegisterInfo.mainRenter.picUrl" 
                  :preview-src-list="[preRegisterInfo.mainRenter.picUrl]">
                </el-image>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 同住人信息 -->
      <div class="section-container" v-if="hasCohabitants">
        <div class="section-title">
          <el-divider content-position="left">同住人信息</el-divider>
        </div>
        <el-table :data="cohabitants" border style="margin-top: 20px">
          <el-table-column label="姓名" prop="name" />
          <el-table-column label="手机号" prop="contacts" />
          <el-table-column label="身份证号" prop="idCardNumber" />
          <el-table-column label="房客类型" align="center">
            <template #default="{ row }">
              <el-tag :type="row.renterType === '1' ? 'success' : 'primary'">
                {{ row.renterType === '1' ? '省内房客' : row.renterType === '2' ? '省外房客' : '--' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="证件照片" align="center">
            <template #default="{ row }">
              <el-image 
                v-if="row.picUrl" 
                style="width: 50px; height: 50px" 
                :src="row.picUrl" 
                :preview-src-list="[row.picUrl]">
              </el-image>
              <span v-else>无</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分配房间信息 -->
      <div class="section-container" v-if="preRegisterInfo.room && preRegisterInfo.room.id">
        <div class="section-title">
          <el-divider content-position="left">房间信息</el-divider>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="房间号">{{ preRegisterInfo.room.name }}</el-descriptions-item>
          <el-descriptions-item label="房间类型">{{ preRegisterInfo.room.typeName }}</el-descriptions-item>
          <el-descriptions-item label="楼层">{{ preRegisterInfo.room.floorName }}</el-descriptions-item>
          <el-descriptions-item label="建筑">{{ preRegisterInfo.room.buildingName }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <!-- 操作按钮区域 -->
      <div class="operation-container">
        <el-button type="info" @click="goBack">取消</el-button>
        <el-button 
          v-if="preRegisterInfo.status === '0'" 
          type="primary" 
          @click="handleAudit">审核</el-button>
        <el-button 
          v-if="preRegisterInfo.status === '1' && (!preRegisterInfo.room || !preRegisterInfo.room.id)" 
          type="warning" 
          @click="handleCheckIn">办理入住</el-button>
      </div>
      
      <!-- 使用可复用的审核对话框组件 -->
      <audit-dialog
        v-model="auditDialogVisible"
        :register-id="preRegisterInfo.registerId"
        @submit="handleAuditSubmit"
      />

      <!-- 使用可复用的办理入住对话框组件 -->
      <check-in-dialog
        v-model="checkInDialogVisible"
        :register-id="preRegisterInfo.registerId"
        @submit="handleCheckInSubmit"
      />
    </el-card>
  </div>
</template>

<script>
import { getInfo, audit, checkIn } from "@/api/room/preregister";
import { listAvailableRooms } from "@/api/room/room";
import AuditDialog from "@/components/preregister/AuditDialog";
import CheckInDialog from "@/components/preregister/CheckInDialog";

export default {
  name: "PreRegisterDetail",
  components: {
    AuditDialog,
    CheckInDialog
  },
  data() {
    return {
      loading: false,
      submitLoading: false,
      preRegisterInfo: {},
      
      // 审核相关
      auditDialogVisible: false,
      auditForm: {
        id: null,
        status: "1",
        remark: ""
      },
      auditRules: {
        status: [
          { required: true, message: "审核结果不能为空", trigger: "change" }
        ]
      },
      
      // 分配房间相关
      assignRoomDialogVisible: false,
      assignRoomForm: {
        id: null,
        roomId: null,
        searchKey: ""
      },
      assignRoomRules: {
        roomId: [
          { required: true, message: "房间不能为空", trigger: "change" }
        ]
      },
      roomOptions: [],
      filteredRoomOptions: [],
      
      // 办理入住相关
      checkInDialogVisible: false
    };
  },
  computed: {
    hasCohabitants() {
      return this.preRegisterInfo.renterList && 
             this.preRegisterInfo.renterList.filter(renter => renter.mainFlag === '2').length > 0;
    },
    cohabitants() {
      if (!this.preRegisterInfo.renterList) return [];
      return this.preRegisterInfo.renterList.filter(renter => renter.mainFlag === '2');
    },
    // 获取租金对象，优先使用rentObject，如果不存在则尝试解析rentInfo
    rentObjectData() {
      if (this.preRegisterInfo.rentObject) {
        return this.preRegisterInfo.rentObject;
      } else if (this.preRegisterInfo.rentInfo) {
        try {
          if (typeof this.preRegisterInfo.rentInfo === 'string') {
            return JSON.parse(this.preRegisterInfo.rentInfo);
          } else {
            return this.preRegisterInfo.rentInfo;
          }
        } catch (e) {
          console.error('解析rentInfo失败:', e);
          return null;
        }
      }
      return null;
    }
  },
  created() {
    this.getPreRegisterInfo();
  },
  methods: {
    // 获取预登记详情
    getPreRegisterInfo() {
      this.loading = true;
      const registerId = this.$route.params.id;
      if (!registerId) {
        this.$modal.msgError("无效的预登记ID");
        this.goBack();
        return;
      }
      
      getInfo(registerId).then(response => {
        if (response.code === 200) {
          this.preRegisterInfo = response.data || {};
        } else {
          this.$modal.msgError(response.msg || "获取预登记详情失败");
          this.goBack();
        }
        this.loading = false;
      }).catch(error => {
        console.error("获取预登记详情失败:", error);
        this.$modal.msgError("获取预登记详情失败");
        this.loading = false;
        this.goBack();
      });
    },
    
    // 获取状态显示类型
    getStatusType(status) {
      switch(status) {
        case '0': return 'info';
        case '1': return 'success';
        case '2': return 'danger';
        case '4': return 'primary'; // 已入住使用主色调
        default: return 'info';
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      switch(status) {
        case '0': return '待审核';
        case '1': return '已审核';
        case '2': return '已拒绝';
        case '4': return '已入住';
        default: return '未知状态';
      }
    },
    
    // 获取租金类型文本
    getRentCollectCycleText(cycle) {
      const cycleNum = parseInt(cycle);
      switch(cycleNum) {
        case 1: return '月租金';
        case 2: return '日租金';
        default: return '未知类型';
      }
    },
    
    // 获取支付方式文本
    getRentTypeText(type) {
      const typeNum = parseInt(type);
      switch(typeNum) {
        case 1: return '每1个月';
        case 2: return '每2个月';
        case 3: return '每3个月';
        case 5: return '每半年';
        case 6: return '每一年';
        case 7: return '一次性';
        default: return '未知方式';
      }
    },
    
    // 刷新数据
    refreshData() {
      this.getPreRegisterInfo();
      this.$modal.msgSuccess("数据已刷新");
    },
    
    // 审核操作
    handleAudit() {
      // 先获取最新数据，确保数据是最新的
      this.loading = true;
      getInfo(this.preRegisterInfo.registerId).then(response => {
        this.loading = false;
        if (response.code === 200) {
          const latestData = response.data || {};
          // 检查状态是否已变更
          if (latestData.status !== '0') {
            this.$modal.msgWarning("当前预登记状态已发生变化，请刷新页面查看最新数据");
            this.preRegisterInfo = latestData;
            return;
          }
          this.auditDialogVisible = true;
        } else {
          this.$modal.msgError(response.msg || "获取最新数据失败");
        }
      }).catch(error => {
        this.loading = false;
        console.error("获取最新数据失败:", error);
        this.$modal.msgError("获取最新数据失败");
      });
    },
    
    // 处理审核提交
    handleAuditSubmit(formData) {
      this.submitLoading = true;
      audit(formData.id, formData.status, formData.remark).then(response => {
        this.submitLoading = false;
        if (response.code === 200) {
          this.$modal.msgSuccess("审核成功");
          this.auditDialogVisible = false;
          this.getPreRegisterInfo(); // 刷新详情
        } else {
          this.$modal.msgError(response.msg || "审核失败");
        }
      }).catch(error => {
        this.submitLoading = false;
        console.error("审核预登记失败:", error);
        this.$modal.msgError("审核失败");
      });
    },
    
    // 分配房间操作
    handleAssignRoom() {
      this.assignRoomDialogVisible = true;
    },
    
    // 处理分配房间提交
    handleAssignRoomSubmit(formData) {
      this.submitLoading = true;
      
      // 调用接口，将租金租期信息作为扩展数据传递
      const params = {
        rentInfo: {
          checkInStart: formData.checkInStart,
          checkInEnd: formData.checkInEnd,
          rentCollectType: formData.rentCollectType,
          rent: formData.rent,
          deposit: formData.deposit,
          rentType: formData.rentType,
          remark: formData.remark
        }
      };
      
      checkIn(formData.id, formData.roomId, params.rentInfo).then(response => {
        this.submitLoading = false;
        if (response.code === 200) {
          this.$modal.msgSuccess("分配房间成功");
          this.assignRoomDialogVisible = false;
          this.getPreRegisterInfo(); // 刷新详情
        } else {
          this.$modal.msgError(response.msg || "分配房间失败");
        }
      }).catch(error => {
        this.submitLoading = false;
        console.error("分配房间失败:", error);
        this.$modal.msgError("分配房间失败");
      });
    },
    
    // 办理入住操作
    handleCheckIn() {
      // 先获取最新数据，确保数据是最新的
      this.loading = true;
      getInfo(this.preRegisterInfo.registerId).then(response => {
        this.loading = false;
        if (response.code === 200) {
          const latestData = response.data || {};
          // 检查状态是否已变更或已分配房间
          if (latestData.status !== '1' || (latestData.room && latestData.room.id)) {
            this.$modal.msgWarning("当前预登记状态已发生变化或已办理入住，请刷新页面查看最新数据");
            this.preRegisterInfo = latestData;
            return;
          }
          this.checkInDialogVisible = true;
        } else {
          this.$modal.msgError(response.msg || "获取最新数据失败");
        }
      }).catch(error => {
        this.loading = false;
        console.error("获取最新数据失败:", error);
        this.$modal.msgError("获取最新数据失败");
      });
    },
    
    // 处理办理入住提交
    handleCheckInSubmit(formData) {
      this.submitLoading = true;
      
      checkIn(formData.id, formData.roomId, formData).then(response => {
        this.submitLoading = false;
        if (response.code === 200) {
          this.$modal.msgSuccess("办理入住成功");
          this.checkInDialogVisible = false;
          this.getPreRegisterInfo(); // 刷新详情
        } else {
          this.$modal.msgError(response.msg || "办理入住失败");
        }
      }).catch(error => {
        this.submitLoading = false;
        console.error("办理入住失败:", error);
        this.$modal.msgError("办理入住失败");
      });
    },
    
    // 返回列表页
    goBack() {
      this.$router.push('/preregister');
    },
    
    // 过滤房间
    filterRooms() {
      if (!this.assignRoomForm.searchKey) {
        this.filteredRoomOptions = [...this.roomOptions];
        return;
      }
      
      this.filteredRoomOptions = this.roomOptions.filter(room => {
        const searchKey = this.assignRoomForm.searchKey.toLowerCase();
        return (
          (room.name && room.name.toLowerCase().includes(searchKey)) ||
          (room.floorName && room.floorName.toLowerCase().includes(searchKey)) ||
          (room.typeName && room.typeName.toLowerCase().includes(searchKey)) ||
          (room.buildingName && room.buildingName.toLowerCase().includes(searchKey))
        );
      });
    }
  }
};
</script>

<style scoped>
.section-container {
  margin-top: 20px;
}
.info-item {
  display: flex;
  margin-bottom: 10px;
}
.info-label {
  font-weight: bold;
  min-width: 80px;
}
.info-value {
  flex: 1;
}
.operation-container {
  margin-top: 30px;
  text-align: right;
}
</style> 